<template>
  <div class="basic_info">
    <div class="info_operation_btn">
      <div class="btn_left">
        <el-button
          @click="onJrybButton(index)"
          v-for="(item, index) in jrybButton"
          :key="index"
          :type="item.state ? 'primary' : ''"
          >{{ item.name }}</el-button
        >
      </div>
      <div class="btn_right">
        <el-button type="primary" v-if="isAudit" style="background: #fd6c21" @click="onBatchAudit()"
          >批量审核</el-button
        >
        <el-button @click="onRefresh">刷新</el-button>
        <el-button type="primary" @click="onClose">关闭</el-button>
      </div>
    </div>
    <div class="info_content_div">
      <div class="div_table">
        <div class="table_content">
          <el-table
            ref="tableRef"
            show-summary
            :summary-method="getSummaries"
            highlight-current-row
            :header-cell-style="{
              color: '#666666',
              textAlign: 'center',
              height: '30px',
              borderColor: '#dddddd',
              background: '#EDEDED',
            }"
            :cell-style="{ textAlign: 'center' }"
            :data="tableData"
            height="100%"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            @row-click="onClickTable"
          >
            <el-table-column type="selection" :selectable="selectionType"> </el-table-column>
            <el-table-column label="序号" prop="xh" width="50px"> </el-table-column>
            <el-table-column label="单据类型" prop="billType_dictText" width="150px">
              <template slot-scope="scope">
                <div class="text_div">
                  <p>{{ scope.row.billType_dictText }}</p>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="单据内容" prop="billConten">
              <template slot-scope="scope">
                <div class="text_div">
                  <p>{{ scope.row.billConten }}</p>
                  <p>
                    <span @click="toDetail(scope.row)">详情</span>
                    <span class="span_pay" v-if="isCollection && !isBaseVersion" @click="toCollection(scope.row)">快速收款</span>
                    <span class="span_pay" v-if="isPayment" @click="toPayment(scope.row)">快速付款</span>
                    <span class="span_audit" v-if="isAudit" @click="toAudit(scope.row)">审核</span>
                  </p>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="table_pagination">
          <div class="pagination_div">
            <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryData.pageNo"
              :page-sizes="[20, 50, 100, 200]"
              :page-size="queryData.pageSize"
              layout="jumper, prev, pager,next, sizes"
              :total="queryData.total"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getAction, postAction, putAction } from '@/api/manage'
import { handlePermissions, handleOtherPerms, handleIsBaseVersion } from '@/utils/index'
import { toBillDetail, toBillAudit } from '@/utils/billUtil'
export default {
  name: 'needHandle',
  inject: ['closeCurrent'],
  computed: {
    ...mapGetters(['name']),
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.tableRef.doLayout()
    })
  },
  created() {
    this.buttonsPermissions = handlePermissions('今日要办')
    this.isBaseVersion = handleIsBaseVersion()
    const data = this.$route.params.state
    if (data) {
      this.stateName = data
    } else {
      this.stateName = '待审核单据'
    }
    this.onButton()
    this.getData()

  
  },
  watch: {
    // 路由变化时，更新数据
    $route: {
      immediate: true,
      handler(val) {
        if (val.name === 'home-needHandle') {
          const data = this.$route.params.state
          if (data && data != this.stateName) {
            this.stateName = data
            this.onButton()
            this.getData()
          }
        }
      },
    },
    tableData: {
      immediate: true,
      handler() {
        setTimeout(() => {
          const table = document.querySelector('.el-table__footer-wrapper>table')
          let tds = table.rows[0].cells
          tds[1].colSpan = 2
          tds[2].style.display = 'none'
          let cell = tds[1].childNodes[0]
          cell.style.justifyContent = 'flex-start'
          cell.style.paddingLeft = '5px'
        }, 0)
      },
    },
  },
  data() {
    return {
      // 存储按钮权限数据
      buttonsPermissions: {},
      // 销售统计按钮切换
      jrybButton: [
        {
          name: '待审核单据',
          state: true,
        },
        {
          name: '待发货单据',
          state: false,
        },
        {
          name: '待收款单据',
          state: false,
        },
        {
          name: '待付款单据',
          state: false,
        },
      ],
      // 表格数据
      tableData: [],
      batchData: [], // 存储多选的数据
      // 查询条件数据
      queryData: {
        pageSize: 20, //每页的数据条数
        pageNo: 1, //默认开始页面
        total: 0, //总记录条数
      },
      stateName: '', // 选中按钮名称
      isAudit: true, // 是否有审核功能
      isCollection: false, // 是否是收款
      isPayment: false, // 是否是付款
      numberOfFailures: 0, //失败个数
      numberOfSuccesses: 0, //成功个数
      isBaseVersion: false,
    }
  },
  methods: {
    // 详情
    toDetail(item) {
      toBillDetail(this, item.billType, item.id)
    },
    getPushTitle(title) {
      // 两个数组个数必须相同
      let diff = ['采购入库单', '采购退货单', '采购换货单', '销售出库单', '销售退货单', '销售换货单']
      let revised = ['采购入库', '采购退货', '采购换货', '销售出库', '销售退货', '销售换货']

      if (diff.includes(title)) {
        let index = diff.indexOf(title)
        return revised[index]
      } else {
        return title
      }
    },
    // 审核
    toAudit(item) {
      let title = this.getPushTitle(item.billType_dictText)
      if (!handlePermissions(title).ShenHe) {
        return this.showTips('未拥有审核权限！')
      }
      // 盘点单审核跳转详情页
      if (item.billType == '9') {
        return toBillDetail(this, item.billType, item.id)
      }
      toBillAudit(item.billType, item.id).then((res) => {
        if (res.code === 200) {
          if (typeof res.result === 'string') {
            if (res.result.indexOf('不能进行审核操作') > -1) {
              this.showTips(res.result, 2)
            } else {
              this.showTips(res.result, 0)
            }
          } else {
            this.showTips('审核成功！', 0)
          }
          this.getData()
        } else if (res.code === 500) {
          this.showTips(res.message, 2)
        }
      })
    },
    // 获取数据
    getData() {
      let data = { ...this.queryData }
      let url
      switch (this.stateName) {
        case '待审核单据':
          url = '/home/home/todayNeedDo/getUnCheckedByPage'
          break
        case '待发货单据':
          url = '/home/home/todayNeedDo/getUnSentByPage'
          break
        case '待收款单据':
          url = '/home/home/todayNeedDo/getUnPayedByPage'
          break
        case '待付款单据':
          url = '/home/home/todayNeedDo/getUnPaymentByPage'
          break
      }
      getAction(url, data).then((res) => {
        if (res.code === 200) {
          this.queryData.total = res.result.total
          let data = res.result.records || []
          data.forEach((item, index) => {
            item.xh = index + 1 // 表格显示的行号码，从1开始
            if (this.isPayment || this.isCollection) {
              item.billConten = `${item.companyId_dictText} ${item.billNumber} 单据id:${item.id}`
            } else {
              item.billConten = `单据编号${item.billNumber} 单据id:${item.id}`
            }
          })
          this.tableData = data
        }
      })
    },
    // 快速收款
    toCollection(value) {
      this.$router.push({
        name: 'paymentManage-paymentBill-billCollectionSettlement',
        params: {
          xghCompanyId: value.companyId,
          source: 'company',
        },
      })
    },
    // 快速付款
    toPayment(value) {
      this.$router.push({
        name: 'paymentManage-paymentBill-billPaymentSettlement',
        params: {
          xghCompanyId: value.companyId,
          source: 'company',
        },
      })
    },
    // 筛选盘点单不能选择
    selectionType(val) {
      return val.billType !== '9'
    },
    // 按钮状态
    onButton() {
      if (this.isBaseVersion) {
        this.jrybButton = [
        { name: '待审核单据',
          state: true, },
        { name: '待收款单据',
          state: false, }
        ]
      }

      this.jrybButton.forEach((item) => {
        if (this.stateName == item.name) {
          item.state = true
        } else {
          item.state = false
        }
      })
      
      this.isAudit = this.stateName === '待审核单据'
      this.isCollection = this.stateName === '待收款单据'
      this.isPayment = this.stateName === '待付款单据'
      this.queryData.pageNo = 1
      this.queryData.pageSize = 20
    },
    // 点击修改价格管理表样式
    onClickTable(row) {
      if (row.billType !== '9') {
        this.$refs.tableRef.toggleRowSelection(row)
      }
    },
    // 点击切换销售统计按钮
    onJrybButton(index) {
      this.stateName = this.jrybButton[index].name
      this.onButton()
      this.getData()
    },
    // 批量审核
    onBatchAudit() {
      if (this.batchData.length === 0) {
        return this.showTips('请先选择需要审核的单据！')
      }
      this.numberOfFailures = 0
      this.numberOfSuccesses = 0
      const loading = this.$loading({
        lock: true,
        text: `批量审核中，当前进度：0/${this.batchData.length}。成功个数：${this.numberOfSuccesses},失败个数：${this.numberOfFailures}`,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.8)',
      });
      setTimeout(() => {
        this.circulationAudit(loading, 0)  
      }, 500);

      // let allAudit = []
      // this.batchData.forEach((item) => {
      //   // 批量审核盘点单的审核跳过
      //   let title = this.getPushTitle(item.billType_dictText)
      //   if (item.billType != '9' && handlePermissions(title).ShenHe) {
      //     allAudit.push(toBillAudit(item.billType, item.id))
      //   }
      // })
      // Promise.all(allAudit).then((res) => {
      //   // 等待所有请求执行完毕
      //   this.showTips('审核成功！', 0)
      //   this.getData()
      // })
    },
    circulationAudit(loading, index) {
      console.log(index);
      
      if (index == this.batchData.length) {
        loading.close()
        this.getData()
        return
      }
      let item = this.batchData[index]
      console.log(item);
      
      toBillAudit(item.billType, item.id).then((res) => {
        if (res.code === 200) {
          if (typeof res.result === 'string') {
            if (res.result.indexOf('不能进行审核操作') > -1) {
              this.numberOfFailures++
            } else {
              this.numberOfSuccesses++
            }
          } else {
            this.numberOfSuccesses++
          }
          
        } else if (res.code === 500) {
          this.numberOfFailures++
        }
        loading.setText(`批量审核中，当前进度：${this.numberOfFailures + this.numberOfSuccesses}/${this.batchData.length}。成功个数：${this.numberOfSuccesses},失败个数：${this.numberOfFailures}`)

        setTimeout(() => {
          this.circulationAudit(loading, ++index)
        }, 100);
      })
    },

    // 刷新
    onRefresh() {
      this.queryData = this.$options.data().queryData
      this.tableData = this.$options.data().tableData
      this.batchData = this.$options.data().batchData
      this.getData()
    },
    // 关闭
    onClose() {
      this.closeCurrent()
    },
    // 触发表格多选按钮
    handleSelectionChange(val) {
      this.batchData = val
    },
    // 合计列计算
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
        } else if (index === 1) {
          sums[index] = '共' + this.queryData.total + '条明细'
        } else {
          sums[index] = ''
        }
      })
      return sums
    },
    // 获取每页几条数据
    handleSizeChange(val) {
      this.queryData.pageSize = val
      this.getData()
    },
    // 获取当前第几页
    handleCurrentChange(val) {
      this.queryData.pageNo = val
      this.getData()
    },
    showTips(msg, type = 1) {
      switch (type) {
        case 0:
          this.$elMessage.success(msg)
          break
        case 1:
          this.$elMessage.warning(msg)
          break
        case 2:
          this.$elMessage.error(msg)
          break
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.basic_info {
  width: 100%;
  height: calc(100vh - 110px);
  background: #f0f2f5;
  box-sizing: border-box;
  padding: 0 8px 8px;
  display: flex;
  flex-direction: column;
}
.info_operation_btn {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  ::v-deep .el-button {
    width: 120px;
    height: 30px;
    text-align: center;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    border-radius: 5px;
    border: none;
    margin-right: 7px;
    margin-left: 0;
    color: #666;
  }
  .el-button--primary {
    color: #fff;
  }
  .btn_left {
    width: 60%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
  .btn_right {
    width: 40%;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    .el-button {
      width: 60px;
    }
  }
}
.info_content_div {
  width: 100%;
  height: calc(100% - 50px);
  background: #fff;
  box-sizing: border-box;
  padding: 8px 8px 0;
  display: flex;
  .div_table {
    width: 100%;
    height: 100%;
    .table_content {
      height: calc(100% - 60px);
      ::v-deep .el-table {
        border: 1px solid #e3e3e3;
        box-sizing: border-box;
        th,
        td {
          padding: 0;
          color: #666;
          box-sizing: border-box;
          border-right: 1px solid #e3e3e3;
          &:last-child {
            border-right: none;
          }
        }
        .el-table-column--selection {
          .cell {
            padding: 0;
            text-align: center;
          }
        }
        .cell {
          line-height: 30px;
          font-size: 12px;
        }
        .text_div {
          display: flex;
          justify-content: space-between;
          padding-right: 38px;
          > p {
            margin: 0;
            > span {
              cursor: pointer;
              color: #1b94fb;
            }
            .span_pay {
              margin-left: 14px;
            }
            .span_audit {
              color: #fd6c21;
              margin-left: 26px;
            }
          }
        }
        // th选择框颜色修改
        .el-checkbox {
          .is-indeterminate {
            .el-checkbox__inner {
              color: #1b93f9;
              background-color: #1b93f9;
              border-color: #1b93f9;
            }
          }
        }
        // td选择框颜色修改
        .is-checked {
          .el-checkbox__inner {
            color: #1b93f9;
            background-color: #1b93f9;
            border-color: #1b93f9;
          }
        }
        .el-table__body tr:hover > td {
          background: #e3f6ff;
        }
        .el-table__footer-wrapper {
          td {
            background: #f4f4f4;
            border: none;
          }
        }
        //滚动条的宽度
        ::-webkit-scrollbar {
          width: 8px;
          height: 10px;
          background-color: #e5e5e5;
        }
        //滚动条的滑块
        ::-webkit-scrollbar-thumb {
          background-color: #c9c9c9;
        }
      }
    }
    .table_pagination {
      width: 100%;
      height: 60px;
      box-sizing: border-box;
      padding: 8px 0;
      display: flex;
      .pagination_div {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-end;
        ::v-deep .el-pagination {
          padding: 0;
          height: 30px;
          .el-pagination__sizes {
            margin: 0;
            .el-input {
              margin-right: 0;
            }
          }
        }
      }
    }
  }
}
</style>

